import tkinter as tk
from tkinter import simpledialog, messagebox
from UI.add_1windows import on_click_button_task_append
from logic.json_function import load_json, save_json
from logic.task_function import del_task
from datetime import datetime
from UI.show_windows import show_info_window

window = tk.Tk

def edit_task(listbox_task, task_information_dict):
    # 获取当前选中的任务索引
    selected_index = listbox_task.curselection()
    if not selected_index:
        messagebox.showwarning("Warning", "Please select a task to edit.")
        return
    
    # 获取选中的任务字符串
    selected_task_str = listbox_task.get(selected_index)
    
    # 解析任务字符串
    task_parts = selected_task_str.split(' priority:')
    task_name = task_parts[0]
    task_priority_str = task_parts[1].split(' due to ')[0]
    task_due_date = task_parts[1].split(' due to ')[1]

    # 找到对应的任务信息
    for key, value in task_information_dict.items():
        if value['task_name'] == task_name and value['task_priority'] == task_priority_str and value['task_due_date'] == task_due_date:
            task_key = key
            break
    else:
        messagebox.showerror("Error", "Task not found in the dictionary.")
        return

    # 弹出对话框让用户编辑任务
    new_task_name = simpledialog.askstring("Input", "Enter new task name:", initialvalue=value['task_name'])
    if new_task_name is None:
        return  # 用户取消输入

    new_task_priority = simpledialog.askstring("Input", "Enter new task priority (high, medium, low):", initialvalue=value['task_priority'])
    if new_task_priority is None:
        return  # 用户取消输入

    new_task_due_date = simpledialog.askstring("Input", "Enter new task due date (YYYY-MM-DD HH:MM:SS):", initialvalue=value['task_due_date'])
    if new_task_due_date is None:
        return  # 用户取消输入

    # 验证输入
    if not new_task_name or not new_task_priority or not new_task_due_date:
        messagebox.showwarning("Input Error", "All fields are required.")
        return

    try:
        due_date = datetime.strptime(new_task_due_date, '%Y-%m-%d %H:%M:%S')
    except ValueError:
        messagebox.showwarning("Input Error", "Invalid date format. Please use YYYY-MM-DD HH:MM:SS.")
        return

    # 更新任务信息
    task_information_dict[task_key]['task_name'] = new_task_name
    task_information_dict[task_key]['task_priority'] = new_task_priority
    task_information_dict[task_key]['task_due_date'] = new_task_due_date

    # 更新 Listbox 显示
    listbox_task.delete(selected_index)
    listbox_task.insert(selected_index, f"{new_task_name} priority:{new_task_priority} due to {new_task_due_date}")

    # 保存更新后的任务信息到 JSON 文件
    save_json('information/task_information.json', task_information_dict)

    # 刷新界面（如果需要）
    window.update(listbox_task, task_information_dict)